package com.icecold.utils;


import cn.hutool.core.io.FileUtil;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Sakura
 * @date 2024/9/30 14:11
 */
public class QRCodeGenerator {

    /**
     * @description: 生成二维码
     * @param text 二维码内容
     * @param remark 二维码描述
     * @param path 二维码保存路径
     * @param logoFile 二维码logo文件
     * @param width 二维码宽度
     * @param height 二维码高度
     * @param fontSize 文字字号
     */
    public static void generateQRCode(String text, String[] remark, String path, File logoFile, int width, int height,Integer fontSize) throws Exception {
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new ConcurrentHashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高纠错等级
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1); // 边框

        // 创建BitMatrix对象
        BitMatrix matrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);

        // 动态计算增加的高度用于备注文本
        int textHeight = (remark != null && remark.length>0) ? 60*remark.length : 0;

        // 创建带有二维码和备注文本的 BufferedImage
        BufferedImage qrImage = new BufferedImage(width+300, height + textHeight+40, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = qrImage.createGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width+300, height + textHeight+40); // 设置背景为白色

        // 绘制二维码到 BufferedImage
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                qrImage.setRGB(150+x, 20+y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        // 添加Logo到二维码
        if (logoFile != null && logoFile.exists()) {
            addLogoToQRCode(qrImage, logoFile, width, height);
        }

        // 添加备注文本
        if (remark != null && remark.length>0) {
            if(fontSize == null){
                fontSize = 20;
            }
            addTextToQRCode(qrImage, remark, width, 20+height, textHeight,fontSize);
        }

        // 保存二维码图片到指定路径
        Path filePath = Paths.get(path);
        Files.createDirectories(filePath.getParent()); // 确保目录存在
        ImageIO.write(qrImage, "PNG", new File(path));
    }

    // 添加Logo到二维码
    private static void addLogoToQRCode(BufferedImage qrImage, File logoFile, int qrWidth, int qrHeight) throws Exception {
        // 读取Logo图片
        BufferedImage logoImage = ImageIO.read(logoFile);

        // 计算Logo的缩放比例和新宽高
        int logoWidth = Math.min(logoImage.getWidth(), qrWidth / 5);  // 缩小至二维码宽度的1/5
        int logoHeight = Math.min(logoImage.getHeight(), qrHeight / 5);

        // 计算Logo绘制的左上角位置，使其居中
        int x = (qrWidth - logoWidth) / 2;
        int y = (qrHeight - logoHeight) / 2;

        // 绘制白色边框背景
        Graphics2D g2 = qrImage.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRoundRect(x - 5, y - 5, logoWidth + 10, logoHeight + 10, 10, 10);

        // 绘制Logo到二维码中心
        g2.drawImage(logoImage.getScaledInstance(logoWidth, logoHeight, Image.SCALE_SMOOTH), x, y, null);
        g2.dispose();
    }

    // 在二维码底部添加文本
    private static void addTextToQRCode(BufferedImage image, String[] text, int width, int qrHeight, int textHeight,Integer fontSize) throws Exception {
        Graphics2D g2 = image.createGraphics();
        g2.setColor(Color.BLACK);
        g2.setFont(new Font("宋体",  Font.BOLD, fontSize));  // 设置字体

        // 获取文本的宽度以便居中对齐
        FontMetrics fm = g2.getFontMetrics();
        int nextHeight = qrHeight;
        for (int i = 0; i < text.length; i++) {
            String text1 = text[i];
            int textWidth = fm.stringWidth(text1);
            int x = (width+300 - textWidth) / 2;

            // 调整 y 坐标位置，将文本稍微上移
            int padding = 10;  // 增加一个 padding 值，让文本上移一点，避免贴得太近
            nextHeight = nextHeight + (60 - fm.getHeight()) / 2 + fm.getAscent() - padding;

            // 绘制文本
            g2.drawString(text1, x, nextHeight);
            nextHeight+=20;
        }
        g2.dispose(); // 释放资源
    }


//    public static void main(String[] args) throws WriterException, IOException {
//        String content = "https://www.zzlmvip.com?sn=32_AB_B1483E4609F47947-DISKSN"; // 二维码内容
//        int width = 500; // 二维码的宽度
//        int height = 500; // 二维码的高度
//        Path file = new File("D:/jeesite/userfiles/qrcode/ceshi.png").toPath(); // 输出文件路径
//
//        QRCodeWriter qrCodeWriter = new QRCodeWriter();
//        BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height);
//
//        // 调整宽度为原宽度的一半
//        int scaledWidth = 1000 ;
//        BitMatrix scaledMatrix = new BitMatrix(scaledWidth, height);
//        for (int x = 0; x < width; x++) {
//            for (int y = 0; y < height; y++) {
//                if (bitMatrix.get(x, y)) {
//                    scaledMatrix.set(x, y);
//                }
//            }
//        }
//
//        MatrixToImageWriter.writeToPath(scaledMatrix, "PNG", file);
//        System.out.println("二维码已生成：" + file.toAbsolutePath().toString());
//    }

    public static String decodeQRCode(String imageUrl)  {
        try {
            // 从网络地址读取图片
            BufferedImage image = ImageIO.read(new URL(imageUrl));
            // 转换为 ZXing 可处理的格式
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            // 解码二维码
            Result result = new MultiFormatReader().decode(bitmap);
            return result.getText();
        } catch (NotFoundException e) {
            throw new RuntimeException("未检测到二维码");
//            return "未检测到二维码";
        } catch (Exception e) {
            throw new RuntimeException("识别失败");
//            return "识别失败: " + e.getMessage();
        }
    }

    public static void main(String[] args) {
        System.out.println(decodeQRCode("http://testbbjz.zzlmvip.com:8005/userfiles/taskpic/2025-03-24/502ec0eda6794209a87aa08aa67aded9.jpg"));
    }
}

